package cn.shop.front.config.interceptor;

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import cn.shop.front.util.JsonUtils;
import cn.shop.transcation.merchantUser.mapper.MerchantUserMapper;
import cn.shop.transcation.merchantUser.mapper.entity.MerchantUser;
import cn.shop.utils.ApiResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 处理商户域名 转换为商户id
 *
 * @author jzw
 * @since 2021-12-30 17:40
 * ------------------
 * @author lyh
 * @since 2022-02-14
 */
@Component
public class MerchantInterceptor implements HandlerInterceptor {

	@Resource
	private MerchantUserMapper mapper;
	/** 增加5秒缓存减少数据库压力 **/
	private static final TimedCache<String, MerchantUser> CACHE = CacheUtil.newTimedCache(5);

	public final static String MERCHANT_USER_KEY = "muId";

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String header = request.getHeader(HttpHeaders.REFERER);
		if (StrUtil.isNotBlank(header)) {
			String domain = ReUtil.get("(?<=://)[a-zA-Z0-9-_]+(?=.)", header, 0);
			MerchantUser merchantUser;
			if (!CACHE.containsKey(domain)) {
				LambdaQueryWrapper<MerchantUser> query = Wrappers.lambdaQuery();
				merchantUser = mapper.selectOne(query);
				CACHE.put(domain, merchantUser);
			} else {
				merchantUser = CACHE.get(domain);
			}
			if (merchantUser != null) {
				request.setAttribute(MERCHANT_USER_KEY, merchantUser.getId());
				return true;
			}
		}
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=utf-8");
		try (PrintWriter writer = response.getWriter()) {
			writer.print(JsonUtils.objectToJson(ApiResult.fail("当前域名无法识别")));
		}
		return false;
	}

}
